import { EventDispatcher } from '../core/EventDispatcher';
import UIMgr from './UIMgr';
import { NetEvent } from '../core/NetEvent';
import PageBaseView from '../view/PageBaseView';
import { PageViewTypeId } from '../define/PageDefine';
import { gameData } from '../tool/GameData';

export default class ViewMgr extends EventDispatcher {
  public static _viewManager: ViewMgr;
  //获取单例对象
  public static get ins(): ViewMgr {
    if (ViewMgr._viewManager == null) {
      ViewMgr._viewManager = new ViewMgr();
      ViewMgr._viewManager.eventInit();
    }
    return ViewMgr._viewManager;
  }

  public eventInit(): void {
    //初始化一些事件
  }

  /**
   * 初始化UI页面容器
   */
  public currentView: cc.Node;
  public currentScript: PageBaseView; //当前pageview页面脚本
  public initView(node: cc.Node, pageScript: PageBaseView): void {
    this.currentView = node;
    this.currentScript = pageScript;
  }

  public openView(view: PageViewTypeId, data: any = null): void {
    if (!view) {
      return;
    }
    this.currentView.active = true;
    this.currentScript.openView(view, data);
  }

  public hint(txt: string, hid?: string): void {
    if (hid && hid === gameData.myPlayer.hid) {
      UIMgr.ins.hint({ txt: txt });
    } else {
      UIMgr.ins.hint({ txt: txt });
    }
  }

  public runViewFunc(view: string, funcName: string, paras: any = null): void {
    if (!view) {
      return;
    }
    this.currentScript.runViewFunc(view, funcName, paras);
  }

  public async closeView(view: PageViewTypeId) {
    await this.currentScript.closeView(view);
    let noview: boolean = true;

    for (let i: number = 0; i < this.currentScript.viewList.length; i++) {
      if (this.currentScript.viewList[i]) {
        noview = false;
        break;
      }
    }
    if (this.currentScript && noview) {
      this.currentView.active = false;
    }
  }

  public async closeAll() {
    await this.currentScript.closeAll();

    this.currentView.active = false;
  }

  /**
   * 获得物品
   */
  public getResTips(resId: number, resNum: number): void {
    //ViewManager.ins.dispatchEvent(Engine.createrEvent(UICommandKey.UIGetResTips,false,false,{type:1,id:resId,num:resNum}));
  }

  /**
   * 发送事件
   */
  public emit(EventType: string, data?: any, bubbles?: boolean, cancelable?: boolean): void {
    let event: any = NetEvent.createrEvent(EventType, bubbles, cancelable, data);
    this.dispatchEvent(event);
  }
}
